package io.xxx.mario.room;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.xxx.mario.room.api.JoinRoomRequest;
import io.xxx.mario.room.api.LeaveRoomRequest;
import jakarta.annotation.Resource;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class RoomService {

    @Resource
    private ModelMapper modelMapper;

    @Resource
    private RoomMapper roomMapper;

    public Page<Room> getPage(Pageable pageable, String name) {
        LambdaQueryWrapper<Room> wrapper = new LambdaQueryWrapper<>();
        Page<Room> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
        if (StringUtils.hasText(name)) {
            wrapper.eq(Room::getName, name);
        }
        return roomMapper.selectPage(page, wrapper);
    }

    public void joinRoom(JoinRoomRequest request) {
        Room room = modelMapper.map(request, Room.class);
        roomMapper.insert(room);
    }

    public void leaveRoom(LeaveRoomRequest request) {
        Room room = modelMapper.map(request, Room.class);
        room.setInRoom(false);
        roomMapper.updateById(room);
    }
}
